﻿using System;
using System.Net.Mail;
using EPiAbstractions;
using EPiServer.Common;
using EPiServer.Common.Comments;
using EPiServer.Community.Blog;
using EPiServer.Core;
using JoelAbrahamsson.BlogExtensions;
using JoelAbrahamsson.PageTypes;

namespace JoelAbrahamsson.Web.Common
{
    public class EmailCommentAddedNotifier : ICommentAddedNotifier
    {
        private IDataFactoryFacade _dataFactoryFacade;

        public EmailCommentAddedNotifier(IDataFactoryFacade dataFactoryFacade)
        {
            _dataFactoryFacade = dataFactoryFacade;
        }

        public void Notify(IComment comment, string commentUrl)
        {
            Entry commentedEntry = (Entry)comment.CommentedEntity;
            Start startPage = (Start)_dataFactoryFacade.GetPage(PageReference.StartPage);
            SmtpClient smtpClient = new SmtpClient();
            foreach (IAuthor subscriber in commentedEntry.GetSubscribers())
            {
                if (subscriber.Email.Equals(comment.Author.Email, StringComparison.InvariantCultureIgnoreCase))
                    continue;

                MailMessage message = new MailMessage("noreply@joelabrahamsson.com", subscriber.Email);
                message.Subject = startPage.CommentNotificationEmailSubjectTemplate;
                message.Subject = message.Subject.Replace("{commentAuthorName}", comment.Author.Name);
                message.Subject = message.Subject.Replace("{entryTitle}", commentedEntry.Title);
                message.Body = startPage.CommentNotificationEmailTemplate;
                message.Body = message.Body.Replace("{recipientName}", subscriber.Name);
                message.Body = message.Body.Replace("{commentAuthorName}", comment.Author.Name);
                message.Body = message.Body.Replace("{entryTitle}", commentedEntry.Title);
                message.Body = message.Body.Replace("{entryUrl}", commentUrl);
                message.IsBodyHtml = true;

                smtpClient.Send(message);
            }
        }
    }
}
